package com.maistars.spider.service.parser.policy.impl;

import com.maistars.spider.service.parser.policy.ParserPolicy;
import com.maistars.spider.service.process.html.HtmlProcessorPipeline;
import com.maistars.spider.service.util.ExtractUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.CollectionUtils;
import us.codecraft.xsoup.Xsoup;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author dhr
 * @date 2021/1/17 上午1:30
 */
public class XPathPolicy implements ParserPolicy {

    private Document document;

    private String content;

    @Override
    public void init(String content) {
        this.content = content;
        this.document =  Jsoup.parse(content);
    }

    @Override
    public List<String> execute(String path,Map<String, String> params) {
        List<String> result = ExtractUtils.getValuesByXPath(document,path);
//        if(CollectionUtils.isEmpty(result)){
//            result = ExtractUtils.getValueByXPath2(document.html(),path);
//        }
        return result;
    }

    public List<Element> executeWithElement(String path, Map<String, String> params) {
        List<Element> result = new ArrayList<>();
        Elements elements = ExtractUtils.getValuesByXPathWithElement(document,path);
        result = elements.subList(0,elements.size());
//        if(CollectionUtils.isEmpty(result)){
//            result = ExtractUtils.getValueByXPath2WithElement(document.html(),path);
//        }
        return result;
    }
}
